//
//  FilterViewController.m
//  WHTestDome
//
//  Created by Assistant on 9/22/25.
//

#import "FilterViewController.h"
#import "TagCollectionViewCell.h"

@interface FilterViewController ()

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableSet<NSNumber *> *selectedIndexSet;
@property (nonatomic, strong) UIView *bottomBar;
@property (nonatomic, strong) UIButton *resetButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIStackView *buttonStack;
@property (nonatomic, strong) UIView *separatorView;

@end

@implementation FilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor systemBackgroundColor];
    self.title = @"筛选";

    if (self.options.count == 0) {
        self.options = @[ @"鲫鲤", @"鲫鱼", @"青鱼", @"草鱼",
                           @"翘嘴鱼", @"鳊鱼", @"罗非鱼", @"鳟鱼",
                           @"鲶鱼", @"鲤鱼", @"昂刺", @"混养",
                           @"鲢白鱼", @"白鲦", @"花鲢", @"黑鱼",
                           @"甲鱼", @"其他鱼", @"杂鱼（翘嘴、鳊鱼）"];
    }

    self.selectedIndexSet = [NSMutableSet set];
    for (NSNumber *idx in self.preselectedIndexes) {
        [self.selectedIndexSet addObject:idx];
    }

    [self setupCollectionView];
    [self setupBottomBar];
}

- (CGFloat)preferredContentHeightWithMax:(CGFloat)maxHeight {
    // Estimate collection content height based on layout and items
    [self.collectionView layoutIfNeeded];
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    CGFloat width = self.collectionView.bounds.size.width > 0 ? self.collectionView.bounds.size.width : UIScreen.mainScreen.bounds.size.width;
    CGFloat x = layout.sectionInset.left;
    CGFloat y = layout.sectionInset.top;
    CGFloat rowHeight = 40.0;
    CGFloat spacing = layout.minimumInteritemSpacing;
    for (NSString *title in self.options) {
        CGSize textSize = [title sizeWithAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16 weight:UIFontWeightRegular] }];
        CGFloat w = ceil(textSize.width) + 24.0 + 16.0; // same as cell size calc
        if (w < 72.0) { w = 72.0; }
        if (x + w + layout.sectionInset.right > width) {
            // New line
            x = layout.sectionInset.left;
            y += rowHeight + layout.minimumLineSpacing;
        }
        x += w + spacing;
    }
    y += rowHeight + layout.sectionInset.bottom;

    // Add bottom bar height
    CGFloat total = y + 72.0; // bottom bar
    return MIN(maxHeight, total);
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 12.0;
    layout.minimumLineSpacing = 12.0;
    layout.sectionInset = UIEdgeInsetsMake(8, 16, 8, 16);

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    self.collectionView.backgroundColor = [UIColor systemBackgroundColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[TagCollectionViewCell class] forCellWithReuseIdentifier:@"tag_cell"];
    [self.view addSubview:self.collectionView];

    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        [self.collectionView.topAnchor constraintEqualToAnchor:guide.topAnchor],
        [self.collectionView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
        [self.collectionView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor]
    ]];
}

- (void)setupBottomBar {
    self.bottomBar = [[UIView alloc] initWithFrame:CGRectZero];
    self.bottomBar.translatesAutoresizingMaskIntoConstraints = NO;
    self.bottomBar.backgroundColor = [UIColor secondarySystemBackgroundColor];
    [self.view addSubview:self.bottomBar];

    self.resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.resetButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.resetButton setTitle:@"重置" forState:UIControlStateNormal];
    [self.resetButton addTarget:self action:@selector(didTapReset) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomBar addSubview:self.resetButton];

    self.confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.confirmButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    self.confirmButton.titleLabel.font = [UIFont boldSystemFontOfSize:17.0];
    [self.confirmButton addTarget:self action:@selector(didTapConfirm) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomBar addSubview:self.confirmButton];

    UILayoutGuide *guide = self.view.safeAreaLayoutGuide;

    // Stack for centered buttons with separator
    self.separatorView = [[UIView alloc] initWithFrame:CGRectZero];
    self.separatorView.translatesAutoresizingMaskIntoConstraints = NO;
    self.separatorView.backgroundColor = [UIColor separatorColor];

    self.buttonStack = [[UIStackView alloc] initWithArrangedSubviews:@[self.resetButton, self.separatorView, self.confirmButton]];
    self.buttonStack.translatesAutoresizingMaskIntoConstraints = NO;
    self.buttonStack.axis = UILayoutConstraintAxisHorizontal;
    self.buttonStack.spacing = 16.0;
    self.buttonStack.alignment = UIStackViewAlignmentCenter;
    [self.bottomBar addSubview:self.buttonStack];

    [NSLayoutConstraint activateConstraints:@[
        [self.bottomBar.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
        [self.bottomBar.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
        [self.bottomBar.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor],

        [self.collectionView.bottomAnchor constraintEqualToAnchor:self.bottomBar.topAnchor],

        [self.confirmButton.widthAnchor constraintEqualToConstant:96.0],
        [self.confirmButton.heightAnchor constraintEqualToConstant:40.0],

        [self.separatorView.widthAnchor constraintEqualToConstant:1.0],
        [self.separatorView.heightAnchor constraintEqualToConstant:20.0],

        [self.buttonStack.centerXAnchor constraintEqualToAnchor:self.bottomBar.centerXAnchor],
        [self.buttonStack.centerYAnchor constraintEqualToAnchor:self.bottomBar.centerYAnchor],

        [self.bottomBar.heightAnchor constraintEqualToConstant:72.0]
    ]];

    // Style buttons
    self.resetButton.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightRegular];
    [self.resetButton setTitleColor:[UIColor labelColor] forState:UIControlStateNormal];

    // Apply green gradient background for confirm button
    self.confirmButton.tintColor = [UIColor whiteColor];
    self.confirmButton.layer.cornerRadius = 20.0;
    self.confirmButton.layer.masksToBounds = YES;
    self.confirmButton.backgroundColor = [UIColor colorWithRed:(54)/255.0 green:(141)/255.0 blue:(246)/255.0 alpha:1.0];
//    CAGradientLayer *gradient = [CAGradientLayer layer];
//    gradient.colors = @[ (id)[UIColor colorWithRed:0.20 green:0.90 blue:0.60 alpha:1.0].CGColor,
//                         (id)[UIColor colorWithRed:0.00 green:0.75 blue:0.50 alpha:1.0].CGColor ];
//    gradient.startPoint = CGPointMake(0, 0.5);
//    gradient.endPoint = CGPointMake(1, 0.5);
//    gradient.cornerRadius = 20.0;
//    [self.confirmButton.layer insertSublayer:gradient atIndex:0];

    // Update gradient frame after layout
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        CAGradientLayer *g = (CAGradientLayer *)weakSelf.confirmButton.layer.sublayers.firstObject;
        g.frame = weakSelf.confirmButton.bounds;
    });
}

#pragma mark - Actions

- (void)didTapReset {
    [self.selectedIndexSet removeAllObjects];
    [self.collectionView reloadData];
}

- (void)didTapConfirm {
    NSMutableArray<NSString *> *selectedOptions = [NSMutableArray array];
    for (NSNumber *idx in self.selectedIndexSet) {
        NSInteger i = idx.integerValue;
        if (i >= 0 && i < (NSInteger)self.options.count) {
            [selectedOptions addObject:self.options[i]];
        }
    }
    // Keep a stable order by sorting indexes
    NSArray<NSNumber *> *sorted = [[self.selectedIndexSet allObjects] sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray<NSString *> *ordered = [NSMutableArray arrayWithCapacity:sorted.count];
    for (NSNumber *n in sorted) {
        NSInteger i = n.integerValue;
        if (i >= 0 && i < (NSInteger)self.options.count) {
            [ordered addObject:self.options[i]];
        }
    }

    if ([self.delegate respondsToSelector:@selector(filterViewController:didConfirmWithSelectedOptions:)]) {
        [self.delegate filterViewController:self didConfirmWithSelectedOptions:ordered.count > 0 ? ordered : selectedOptions];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.options.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TagCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tag_cell" forIndexPath:indexPath];
    BOOL selected = [self.selectedIndexSet containsObject:@(indexPath.item)];
    [cell configureWithTitle:self.options[indexPath.item] selected:selected];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *idx = @(indexPath.item);
    if ([self.selectedIndexSet containsObject:idx]) {
        [self.selectedIndexSet removeObject:idx];
    } else {
        [self.selectedIndexSet addObject:idx];
    }
    [collectionView reloadItemsAtIndexPaths:@[indexPath]];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.options[indexPath.item];
    CGFloat horizontalPadding = 24.0; // 12 on each side inside the chip
    CGSize textSize = [title sizeWithAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16 weight:UIFontWeightRegular] }];
    CGFloat width = ceil(textSize.width) + horizontalPadding + 16.0; // outer padding
    if (width < 72.0) { width = 72.0; }
    CGFloat height = 40.0;
    return CGSizeMake(width, height);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(collectionView.bounds.size.width, 44.0);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        static NSString *headerId = @"header";
        [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId forIndexPath:indexPath];
        // Clear old
        [header.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.translatesAutoresizingMaskIntoConstraints = NO;
        label.text = self.titleName.length>0?self.titleName:@"标题名称";
        label.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold];
        label.textColor = [UIColor labelColor];
        [header addSubview:label];
        [NSLayoutConstraint activateConstraints:@[
            [label.leftAnchor constraintEqualToAnchor:header.leftAnchor constant:20.0],
            [label.bottomAnchor constraintEqualToAnchor:header.bottomAnchor constant:-6.0]
        ]];
        return header;
    }
    return [UICollectionReusableView new];
}

@end


